package com.msb.mall.producet.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.msb.common.constant.ProductConstant;
import com.msb.common.dto.MemberPrice;
import com.msb.common.dto.SkuHasStockDTO;
import com.msb.common.dto.es.SkuESModel;
import com.msb.common.dto.SkuReductionDTO;
import com.msb.common.dto.SpuBoundsDTO;
import com.msb.common.utils.R;
import com.msb.mall.producet.entity.*;
import com.msb.mall.producet.feign.CouponFeignService;
import com.msb.mall.producet.feign.SearchFeignService;
import com.msb.mall.producet.feign.WareSkuFeignService;
import com.msb.mall.producet.service.*;
import com.msb.mall.producet.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.common.utils.PageUtils;
import com.msb.common.utils.Query;

import com.msb.mall.producet.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    WareSkuFeignService wareSkuFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    BrandService brandService;

    @Autowired
    AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * 保存商品的发布信息
     *
     * @param spuInfoVO
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuInfoVO spuInfoVO) {
        // 1. 保存spu的基本信息  pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfoVO, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        spuInfoEntity.setPublishStatus(0); // 0 - 新建，1 - 上架  2-下架
        this.save(spuInfoEntity);

        // 2. 保存spu的详情信息 --其实就是图片 图片内存是商品详情介绍  pms_spu_info_desc
        List<String> decripts = spuInfoVO.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        descEntity.setDecript(String.join(",", decripts));
        spuInfoDescService.save(descEntity);

        // 3. 保存spu的图片信息  pms_spu_images
        List<String> images = spuInfoVO.getImages();
        List<SpuImagesEntity> imagesEntities = images.stream().map(e -> {
            SpuImagesEntity entity = new SpuImagesEntity();
            entity.setSpuId(spuInfoEntity.getId());
            entity.setImgUrl(e);
            return entity;
        }).collect(Collectors.toList());
        spuImagesService.saveBatch(imagesEntities);

        // 4. 保存规格参数信息  pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuInfoVO.getBaseAttrs();
        //封装规格参数数据
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(e -> {
            ProductAttrValueEntity entity = new ProductAttrValueEntity();
            entity.setSpuId(spuInfoEntity.getId());
            entity.setAttrId(e.getAttrId());
            entity.setAttrValue(e.getAttrValues());
            AttrEntity attrEntity = attrService.getById(e.getAttrId());
            entity.setAttrName(attrEntity.getAttrName());
            entity.setQuickShow(e.getShowDesc());
            return entity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntities);


        // 5. 保存当前spu对应的所有的sku信息
        List<Skus> skus = spuInfoVO.getSkus();
        if (skus != null && skus.size() > 0) {
            //    5.1 保存sku的基本信息  pms_sku_info
            skus.forEach(item -> {
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSaleCount(0L);

                List<Images> images1 = item.getImages();
                String defaultImg = "";
                for (Images images2 : images1) {
                    if (images2.getDefaultImg() == 1) {
                        defaultImg = images2.getImgUrl();
                    }
                }
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.save(skuInfoEntity);


                //    5.2 保存sku的图片信息  pms_sku_images
                List<SkuImagesEntity> skuImagesEntities = images1.stream().map(img -> {
                            SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                            skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                            skuImagesEntity.setImgUrl(img.getImgUrl());
                            skuImagesEntity.setDefaultImg(img.getDefaultImg());
                            return skuImagesEntity;
                        }).filter(e -> e.getDefaultImg() == 1)//为空的图片不用保存
                        .collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);


                // todo   5.3 保存满减  折扣  会员价  远程调用   mall-sms: sms_sku_ladder, sms_sku_full_reduction, sms_member_price
                SkuReductionDTO dto = new SkuReductionDTO();
                BeanUtils.copyProperties(item, dto);
                dto.setSkuId(skuInfoEntity.getSkuId());
                //设置会员价
                if (item.getMemberPrice() != null && item.getMemberPrice().size() > 0) {
                    List<MemberPrice> list = item.getMemberPrice().stream().map(memberPrice -> {
                        MemberPrice mDto = new MemberPrice();
                        BeanUtils.copyProperties(memberPrice, mDto);
                        return mDto;
                    }).collect(Collectors.toList());
                    dto.setMemberPrice(list);
                }
                R r = couponFeignService.saveFullReductionInfo(dto);
                if (r.getCode() != 0) {
                    log.error("远程调用Coupon服务处理满减  折扣  会员价信息失败, skuId: " + skuInfoEntity.getSkuId());
                }

                //    5.4 保存sku的销售属性组合信息  pms_sku_sale_attr_value
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);

                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
            });
        }
        // 6. 保存spu的积分信息  mall-sms: sms_spu_bounds
        Bounds bounds = spuInfoVO.getBounds();
        SpuBoundsDTO spuBoundsDTO = new SpuBoundsDTO();
        BeanUtils.copyProperties(bounds, spuBoundsDTO);
        spuBoundsDTO.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundsDTO);
        if (r.getCode() != 0) {
            log.error("远程调用Coupon服务存储积分信息失败, skuId: " + spuInfoEntity.getId());
        }


    }


    /**
     * spu信息检索  分页查询   分类 品牌 状态 关键字
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        //设置对应的检索条件
        //关键字
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(
                    w -> w.eq("id", key)
                            .or().like("spu_name", key)
                            .or().like("spu_description", key));
        }

        //状态
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);
        }

        //catelogId
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equals(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }

        //brandId
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equals(brandId)) {
            wrapper.eq("brand_id", brandId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        //查询分类名称和品牌名称
        List<SpuInfoEntity> records = page.getRecords();
        List<SpuInfoVO> data = records.stream().map(e -> {
            Long catalogId = e.getCatalogId();
            CategoryEntity categoryEntity = categoryService.getById(catalogId);

            Long _brandId = e.getBrandId();
            BrandEntity brandEntity = brandService.getById(_brandId);

            SpuInfoVO spuInfoVO = new SpuInfoVO();
            BeanUtils.copyProperties(e, spuInfoVO);
            spuInfoVO.setCatalogName(categoryEntity.getName());
            spuInfoVO.setBrandName(brandEntity.getName());

            return spuInfoVO;
        }).collect(Collectors.toList());

        IPage<SpuInfoVO> _page = new Page<>();
        _page.setRecords(data);
        _page.setCurrent(page.getCurrent());
        _page.setSize(page.getSize());
        _page.setPages(page.getPages());
        _page.setTotal(page.getTotal());


        return new PageUtils(_page);
    }

    /**
     * 实现商品上家   商品相关桑数据存储到es中    更新spu状态
     * @param spuId
     */
    @Override
    public void spuUp(Long spuId) {
        //根据spuid找到对应的sku信息
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);

        //对应的规格参数  pms_product_attr_value
        List<SkuESModel.Attrs> attrsModel = getAttrsModel(spuId);

        //根据所有的skuId  一次远程调用  获取对应的库存信息
        //拿到所有的skuId
        List<Long> skuIds = skus.stream().map(e -> e.getSkuId()).collect(Collectors.toList());
        Map<Long, Boolean> hasStockMap = getSkuHasStock(skuIds);


        List<SkuESModel> skuESModels = skus.stream().map(item -> {
            SkuESModel skuESModel = new SkuESModel();

            //实现属性的赋值
            BeanUtils.copyProperties(item, skuESModel);
            skuESModel.setSubTitle(item.getSkuTitle());
            skuESModel.setSkuPrice(item.getPrice());
            skuESModel.setSkuImg(item.getSkuDefaultImg());


            //是否有库存  去库存系统查询  一次远程调用获取所有skuId对应的库存信息
            if (hasStockMap == null) {
               skuESModel.setHasStock(true);
            } else {
                skuESModel.setHasStock(hasStockMap.get(item.getSkuId()));
            }


            //hotScore 热度分  ->  默认给0即可
            skuESModel.setHotScore(0l);

            //品牌和类型名称
            BrandEntity brand = brandService.getById(item.getBrandId());
            CategoryEntity category = categoryService.getById(item.getCatalogId());
            skuESModel.setBrandName(brand.getName());
            skuESModel.setBrandImg(brand.getLogo());
            skuESModel.setCatalogName(category.getName());

            //封装规格参数
            skuESModel.setAttrs(attrsModel);

            return skuESModel;
        }).collect(Collectors.toList());


        // 6. 调用es服务  存储数据 skuESModels
        R r = searchFeignService.productStatusUp(skuESModels);

        //根据对应的状态更新商品的状态
        if (r.getCode() == 0) {
            //远程调用成功  --更新商品的状态为上架
            baseMapper.updateSpuStatusUp(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        } else {
            //远程调用失败
        }
    }

    /**
     * 根据spuId查询对应的规格参数信息
     * @param spuId
     * @return
     */
    private List<SkuESModel.Attrs> getAttrsModel(Long spuId) {
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrsForSpuId(spuId);
        List<Long> attrIds = baseAttrs.stream().map(e -> e.getAttrId()).collect(Collectors.toList());

        //pms_attr 中的search_type字段决定属性是否可检索
        //查询出所有可检索的规格参数编号
        List<Long> searchIds = attrService.selectSearchAttrIds(attrIds);

        //baseAttrs 过滤   封装
        List<SkuESModel.Attrs> attrsModel = baseAttrs.stream().filter(e -> searchIds.contains(e.getAttrId())).map(e->{
            SkuESModel.Attrs attrs = new SkuESModel.Attrs();
            attrs.setAttrId(e.getAttrId());
            attrs.setAttrName(e.getAttrName());
            attrs.setAttrValue(e.getAttrValue());
            return attrs;
        }).collect(Collectors.toList());
        return attrsModel;
    }


    /**
     * 获取每个sku对应的库存
     * @param skuIds
     * @return
     */
    private Map<Long, Boolean> getSkuHasStock(List<Long> skuIds) {
        if (skuIds == null || skuIds.size() == 0) {
            return null;
        }
        try {
            //远程调用
            List<SkuHasStockDTO> skusHasStock = wareSkuFeignService.getSkusHasStock(skuIds);
            Map<Long, Boolean> result = skusHasStock.stream().collect(Collectors.toMap(SkuHasStockDTO::getSkuId, SkuHasStockDTO::getHasStock));
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}